package com.pet.petadoption.utils.compont;


import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {
    //在控制器接受请求之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        System.out.println("preHandle==>sessionId"+request.getSession().getId());

        //获取session作用域中的数据
        String account=(String)request.getSession().getAttribute("username");
        System.out.println("preHandle ========= >"+account);
        if(account==null||account.equals("")){
            System.out.println("拦截"+request.getRequestURI()+"的请求");
            //重定向到登录页面
            System.out.println("重定向页面");
//            response.sendRedirect("/user/log");
            return false; //程序到此结束
        }else{
            System.out.println("通过拦截器"+request.getRequestURI()+ "   ");
            return true;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("我获取到了一个返回的结果：" + response.toString());
        System.out.println("请求结束了");
    }

}
